// 1.引入express
const express = require('express');
// 2.创建应用对象
const app = express();
// 3.创建路由规则
// request是对请求报文的封装
// response是对响应报文的封装
// app.all可以接受任意类型的请求

// IE缓存
app.get('/ie', (request, response) => {
        response.setHeader('Access-Control-Allow-Origin', '*');
        response.send('hello express001');
    })
    // json响应
app.post('/json-server', (request, response) => {
        // 设置请求头,设置允许跨域
        response.setHeader('Access-Control-Allow-Origin', '*');
        // 设置响应体
        // 对对象进行字符串转换
        const data = {
            name: 'atguigu',
        }
        let str = JSON.stringify(data);
        response.send(str);
    })
    // 延时响应
app.all('/delay', (request, response) => {
        response.setHeader('Access-Control-Allow-Origin', '*');
        setTimeout(() => {
            response.send('延时3s响应');
        }, 3000);
    })
    // jQuery Ajax
app.all('/jquery', (request, response) => {
        response.setHeader('Access-Control-Allow-Origin', '*');
        response.setHeader('Access-Control-Allow-Headers', '*');
        //response.send('hello jquery ajax');
        const data = { name: 'jquery ajax' }
        response.send(JSON.stringify(data));
    })
    // Axios Ajax
app.all('/axios', (request, response) => {
        response.setHeader('Access-Control-Allow-Origin', '*');
        response.setHeader('Access-Control-Allow-Headers', '*');
        //response.send('hello axios ajax');
        const data = { name: 'axios发送ajax' }
        response.send(data);
    })
    // fetch发送ajax请求
app.all('/fetch', (request, response) => {
        response.setHeader('Access-Control-Allow-Origin', '*');
        response.setHeader('Access-Control-Allow-Headers', '*');
        // response.send('hello fetch ajax');
        const data = { name: 'axios发送ajax' }
        response.send(JSON.stringify(data));
    })
    // 原生jsonp
app.get('/jsonp', (request, response) => {
        response.setHeader('Access-Control-Allow-Origin', '*');
        // response.send('console.log("hello jsonp")');
        const data = {
            name: '尚硅谷atguigu',
            exist: 1,
            msg: '用户名已经存在'
        }
        let str = JSON.stringify(data);
        response.end(`handle(${str})`);
    })
    // jquery发送jsonp请求
app.all('/jquery-jsonp', (request, response) => {
    response.setHeader('Access-Control-Allow-Origin', '*');
    const data = {
        name: 'atguigu',
        city: ['北京', '上海', '广东']
    }
    let str = JSON.stringify(data);
    // 接受callback参数
    let cb = request.query.callback;
    response.end(`${cb}(${str})`);
})
app.all('/cors', (request, response) => {
    // 设置响应头，允许跨域
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.send('hello CORS');
})
app.listen(8000, () => {
    console.log('服务已经启动, 8000 端口监听中...')
})